<template>
  <el-dialog v-if="visible" v-model="visible" width="514px" title="修改店铺" :close-on-click-modal="false" :show-close="false" :close-on-press-escape="false">
    <div class="storeItem_list">
      <el-checkbox v-model="monthlyData.allChecked" :label="true" @change="(val) => onChange(val)">全选</el-checkbox>
      <el-checkbox-group v-model="monthlyData.checked" @change="(val) => onSupplierChange(val)">
        <el-checkbox class="cateItems" v-for="supplier in monthlyData.list" :key="supplier.supplierId" :label="supplier.supplierId"> {{ supplier.supplierName }} </el-checkbox>
      </el-checkbox-group>
    </div>

    <template #footer>
      <Button label="取消" @click="onCancelClick" />
      <Button label="确认" type="primary" @click="onConfirmClick" />
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, computed, ref, onMounted, watch } from 'vue'
import api from '@/api'
import { ElMessage } from 'element-plus'
import Button from '@/components/button/button.vue'

const props = defineProps(['visible', 'list'])
const emit = defineEmits(['update:visible', 'complete'])

const visible = computed({
  get: () => {
    return props.visible
  },
  set: (value) => emit('update:visible', value)
})

watch(
  () => props.list,
  (val) => {
    if (val) {
      monthlyData.supplierIds = val
      supplierMonthlyStoreData()
    }
  }
)

const loading = ref(false)
const isShow = ref(false)

const monthlyData = reactive({
  checked: [],
  allChecked: '',
  supplierIds: [],
  list: []
})

const supplierMonthlyStoreData = async () => {
  loading.value = true
  let url = `/medinstrument/boss/supplier/allSupplierList?monthlyFlag=YES`
  let { data, err } = await api.get(url)
  loading.value = false
  if (err) {
    ElMessage.error(err)
  } else {
    monthlyData.list = data.list
    let arr = monthlyData.supplierIds.map((e) => {
      return monthlyData.list.find((f) => e === f.supplierId)
    })

    // if (monthlyData.checked.length === monthlyData.supplierIds.length) {
    //   monthlyData.allChecked = true
    // }
    monthlyData.checked = arr.map((e) => e.supplierId)
  }
}

const onChange = (val) => {
  if (val) {
    monthlyData.checked = monthlyData.list.map((e) => e.supplierId)
  } else {
    monthlyData.checked = []
  }
}

const onSupplierChange = (val) => {
  monthlyData.checked = Object.assign([], val)
  monthlyData.allChecked = monthlyData.list.length === monthlyData.checked.length
}

const onCancelClick = () => {
  visible.value = false
}

const onConfirmClick = () => {
  emit('complete', monthlyData.checked)
  visible.value = false
}
</script>

<style scoped lang="scss">
.storeItem_list {
  padding-top: 10px;
  .cateItems {
    margin-right: 40px;
  }
}
</style>
